import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Card, Row, Input, Button, Col, List, InputNumber, Spin, Divider, Form, Modal } from 'antd';
import SimpleSelection from './SimpleSelectionPage';
import PaperTitleForm from './titleForm'

const FormItem = Form.Item;

@connect(({ paper, loading }) => ({
  paperTitle: paper.paperTitle,
  columnList: paper.columnList,
  questionList: paper.questionList,
  editColumnLoading: loading.effects['paper/setExamColumn'],
  newQuestionLoading: loading.effects['paper/createExamQuestion','paper/deleteExamQuestion'],
}))
@Form.create()
class PaperSetting extends PureComponent {
  state = {
    titleDisplay: true,
    visible: false,
    editColumn: {},
  }

  // componentDidMount() {
  //   const { dispatch } = this.props;
  //   dispatch({
  //     type: 'paper/getExaminationPaper',
  //     callback: (res) => {
  //       if (res.id) {
  //         dispatch({
  //           type: 'paper/getExaminationColumn',
  //           payload: {
  //             paperId: res.id
  //           },
  //           callback: (quesRes) => {
  //             if (quesRes) {
  //               dispatch({
  //                 type: 'paper/getExaminationQuestionByColumn',
  //                 payload: {
  //                   columnIds: quesRes
  //                 }
  //               })
  //             }
  //           }
  //         });
  //       }
  //     }
  //   });
  // }

  onClick = () => {
    this.setState({
      titleDisplay: false,
    })
  }

  newColumn = () => {
    const { dispatch, paperTitle } = this.props;
    dispatch({
      type: 'paper/createExamColumn',
      payload: {
        paperId: paperTitle.id
      },
      callback:(res)=>{
        console.log(res)
        dispatch({
          type: 'paper/getExaminationQuestionByColumn',
          payload: {
            columnIds: res,
          }
        })
      }
    })
  }

  newQuestion = (item) => {
    const { dispatch } = this.props;
    // console.log(item)
    dispatch({
      type: 'paper/createExamQuestion',
      payload: {
        columnId: item.id,
      }
    })
  }

  editColumn = (column) => {
    this.setState({
      visible: true,
      editColumn: column,
    });
  }

  deleteColumn = (column) => {
    const { dispatch } = this.props
    dispatch({
      type: 'paper/deleteExamColumn',
      payload: {
        ...column,
      }
    })
  }

  handleCancel = () => {
    this.setState({
      visible: false,
    });
  }

  handleOk = (e) => {
    this.handleSubmit(e)
  }

  handleSubmit = (e) => {
    const { form, dispatch } = this.props;
    const { editColumn } = this.state;
    form.validateFields((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
        dispatch({
          type: 'paper/setExamColumn',
          payload: {
            id: editColumn.id,
            paperId: editColumn.paperId,
            ...values,
          },
          callback: (res) => {
            if (res) {
              this.setState({
                visible: false,
                editColumn: {},
              });
            }
          }
        })
      }
    });
  }

  titleCallback = () => {
    this.setState({
      titleDisplay: true,
    })
  }

  render() {
    const {
      form: { getFieldDecorator }, paperTitle, columnList, editColumnLoading, questionList, newQuestionLoading
    } = this.props;

    const { titleDisplay, editColumn } = this.state;
    // console.log(editColumnLoading,newQuestionLoading)

    const formItemLayout = {
      labelCol: {
        lg: { span: 5 },
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        lg: { span: 19 },
        xs: { span: 24 },
        sm: { span: 19 },
      },
    };

    const titleShow = (
      <Row gutter={24} type="flex" justify="center">
        <Col>
          <h2 style={{ fontWeight: `bold`, fontSize: 30, fontFamily: `fantasy` }}>{paperTitle && paperTitle.title}</h2>
        </Col>
        <Col lg={2} style={{ paddingTop: 10 }}>
          <Button onClick={this.onClick} type="ghost">修改</Button>
        </Col>
      </Row>
    )

    const columnListCard = columnList.map((item, index) => (
      <Card
        key={item.id}
        title={
          <span>
            <Divider style={{ color: `red` }} type="vertical" />
            {item.title}
            <Divider style={{ color: `red` }} type="vertical" />
            {item.totalScore}
          </span>
        }
        bordered={false}
        style={{ marginTop: 8 }}
        // bodyStyle={{ padding: 0 }}
        headStyle={{ backgroundColor: `#EEEEEE` }}
        extra={
          <span>
            <Button onClick={() => this.editColumn(item)}>修改</Button>
            <Button onClick={() => this.deleteColumn(item)}>删除</Button>
          </span>}
      >
        <List
          rowKey="id"
          // grid={{ gutter: 24, lg: 4, md: 3, sm: 2, xs: 1 }}
          dataSource={questionList[index]}
          renderItem={quesItem => quesItem ? (
            <List.Item>
              <SimpleSelection question={quesItem} />
            </List.Item>
          ):(
            <List.Item>
              <Button onClick={() => this.newQuestion(item)}>新建题目</Button>
            </List.Item>
          )
          }
        />

      </Card>
    ))

    const columnCreate = (
      <Card
        bodyStyle={{ backgroundColor: `#EEEEEE` }}
        style={{ marginTop: 15 }}
      >
        <Button onClick={this.newColumn} type="default">新建栏目</Button>
      </Card>
    )

    return (
      <div>
        <Spin spinning={newQuestionLoading ? true : false}>
          <Card>
            {
              titleDisplay ? titleShow : <PaperTitleForm paperTitle={paperTitle} callback={this.titleCallback} />
            }
          </Card>
          <Modal
            title="新增竞赛"
            visible={this.state.visible}
            onOk={this.handleOk}
            onCancel={this.handleCancel}
            confirmLoading={editColumnLoading}
            destroyOnClose
          >
            <Form {...formItemLayout} onSubmit={this.handleSubmit}>
              <FormItem label="栏目标题">
                {getFieldDecorator('title', {
                  rules: [{ required: true, }],
                  initialValue: editColumn && editColumn.title
                })(<Input />)}
              </FormItem>
              <FormItem label="栏目总分">
                {getFieldDecorator('totalScore', {
                  rules: [{ required: true, type: "number", min: 1, max: 100 }],
                  initialValue: editColumn && editColumn.totalScore
                })(<InputNumber />)}
              </FormItem>
              <FormItem label="栏目简介">
                {getFieldDecorator('columnBackup', {
                  initialValue: editColumn && editColumn.columnBackup
                })(<Input.TextArea autosize={{ minRows: 2, maxRows: 4 }} />)}
              </FormItem>
              <FormItem label="排序">
                {getFieldDecorator('sort', {
                  rules: [{ type: "number", min: 0, max: 100 }],
                  initialValue: editColumn && editColumn.sort
                })(<InputNumber />)}
              </FormItem>
            </Form>
          </Modal>
          {columnList.length > 0 ? columnListCard : columnCreate}

          {columnList.length > 0 ? columnCreate : null}
        </Spin>
      </div>

    )
  }
}
export default PaperSetting